/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode curA = headA;
        ListNode curB = headB;

        //短数组长度
        while (curA != null && curB != null){
            curA = curA.next;
            curB = curB.next;
        }

        //headA 短,此时curB 指向第shortNum个节点
        if(curA == null){
            ListNode preA = headA;
            ListNode preB = headB;

            while (curB != null){
                curB = curB.next;
                preB = preB.next;
            }

            ListNode res = preA;
            while (preB.next != curB){
                if (preA != preB) res = preA.next;
                preA = preA.next;
                preB = preB.next;
            }
            if (preA != preB) return null;
            return res;

        }else {
            ListNode preA = headA;
            ListNode preB = headB;

            while (curA != null){
                curA = curA.next;
                preA = preA.next;
            }

            ListNode res = preB;
            while (preA.next != curA){
                if (preA != preB) res = preB.next;
                preA = preA.next;
                preB = preB.next;
            }
            if (preA != preB) return null;
            return res;

        }

    }
}